/**
 * Created by rwp on 2016/8/25.
 * 购物车
 * 依赖 https://github.com/florian/cookie.js
 * 后台获取 cart值需要解码2次
 */

(function(){
    // 物品对象固定属性id和num、price
    var _default = {
        // 数量
        aliasNum: 'num',
        // 单价
        aliasPrice: 'price',
        // 是否使用Cookie
        useCookie: true,
        // 天数
        expiresCookie: 7,
        debug: false
    };
    Cart = {
        options: _default
    };

    var hasFromCookie = false;
    // 存储所有对象
    var _all = {};

    Cart.all = function(){
        Cart.saveFromCookie();
        return this._all(_all);
    };

    Cart.get = function(id){
        Cart.saveFromCookie();
        if(!!!_all[id]){
            return null;
        }
        return this.parse(_all[id]);
    };

    Cart.remove = function(id){
        Cart.saveFromCookie();
        if(!!_all[id]){
            delete _all[id];
            this.saveToCookie();
        }
    };

    Cart.empty = function(){
        Cart.saveFromCookie();
        for(var _id in _all){
            if(!!_all[_id]){
                delete _all[_id];
            }
        }
        this.saveToCookie();
    };

    Cart.set = function(id, num, attrs){
        Cart.saveFromCookie();
        Cart._set(id, num, attrs);
        this.saveToCookie();
    };

    Cart.setAttrs = function(id, attrs){
        Cart.saveFromCookie();
        if(!!attrs && typeof attrs === 'object' && !!_all[id]){
            _all[id].price = /^\d+(\.\d{1,2})?$/.test(attrs[this.options.aliasPrice]) ? attrs[this.options.aliasPrice] : 0;
            _all[id].attrs = attrs;
            this.saveToCookie();
        }
    };

    Cart.totalPrice = function(){
        var total = 0;
        for(var _id in _all){
            total += _all[_id].num * _all[_id].price;
        }
        return total;
    };

    // 保存到Cookie
    Cart.saveToCookie = function(){
        if (this.options.useCookie){
            if(this.options.debug){
                console.log(JSON.stringify(this.all()));
            }
            cookie.set('cart', encodeURIComponent(JSON.stringify(_all)), {
                expires: this.options.expiresCookie,
                path: '/'
            });
        }
    };

    // 从Cookie中获取
    Cart.saveFromCookie = function(){
        if (this.options.useCookie && !hasFromCookie){
            var str = cookie.get('cart');
            if(str + '' != 'undefined'){
                if(this.options.debug){
                    console.log(str);
                }
                var _0all =  eval('('+decodeURIComponent(str)+')');
                if(this.options.debug){
                    console.log(_0all);
                }
                for (var id in _0all){
                    this._set(id, _0all[id].num, _0all[id].attrs);
                }
                if(this.options.debug){
                    console.log(_all);
                }
            }

            hasFromCookie = true;
        }
    };

    Cart.getFromCookie = function(){
        if (this.options.useCookie){
            var str = cookie.get('cart');
            if(str + '' != 'undefined') {
                if (this.options.debug) {
                    console.log(str);
                }
                var _0all = eval('(' + decodeURIComponent(str) + ')');
                return this._all(_0all);
            }
        }
        return null;
    }

    Cart._set = function(id, num, attrs){
        if(!id || !num){
            return;
        }
        if(typeof _all[id] == 'undefined'){
            _all[id] = {
                id: id
            };
        }
        _all[id].num = /^\d+$/.test(num) ? num : 0;
        _all[id].price = /^\d+(\.\d{1,2})?$/.test(attrs[this.options.aliasPrice]) ? attrs[this.options.aliasPrice] : 0;
        if(!!attrs && typeof attrs === 'object'){
            _all[id].attrs = attrs;
        }
    };

    Cart._all = function(_1all){
        var all = [];
        for(var _key in _1all){
            all.push(this.parse(_1all[_key]));
        }
        return all;
    };

    Cart.parse = function(obj){
        var _obj = {};
        for(var _attr in obj.attrs){
            _obj[_attr] = obj.attrs[_attr];
        }
        // 最后赋上 数量
        _obj[this.options.aliasNum] = obj.num;
        return _obj;
    };

    // If an AMD loader is present use AMD.
    // If a CommonJS loader is present use CommonJS.
    // Otherwise assign the `cookie` object to the global scope.
    if (typeof define === 'function' && define.amd) {
        define(function () {
            return Cart;
        });
    } else if (typeof exports !== 'undefined') {
        exports.Cart = Cart;
    } else window.Cart = Cart;

})();